import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  id: number
  username: string
  name: string
  avatar: string
  loginTime: string
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => isLoggedIn.value && userInfo.value !== null)

  // 初始化认证状态
  const initAuth = () => {
    const storedUserInfo = localStorage.getItem('userInfo')
    const storedLoginStatus = localStorage.getItem('isLoggedIn')
    
    if (storedUserInfo && storedLoginStatus === 'true') {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
        isLoggedIn.value = true
      } catch (error) {
        console.error('解析用户信息失败:', error)
        clearAuth()
      }
    }
  }

  // 登录
  const login = (user: UserInfo) => {
    userInfo.value = user
    isLoggedIn.value = true
    
    // 保存到localStorage
    localStorage.setItem('userInfo', JSON.stringify(user))
    localStorage.setItem('isLoggedIn', 'true')
  }

  // 登出
  const logout = () => {
    clearAuth()
  }

  // 清除认证信息
  const clearAuth = () => {
    userInfo.value = null
    isLoggedIn.value = false
    
    // 清除localStorage
    localStorage.removeItem('userInfo')
    localStorage.removeItem('isLoggedIn')
  }

  // 检查用户权限
  const hasPermission = (permission: string): boolean => {
    if (!isAuthenticated.value) return false
    
    // 这里可以根据实际需求实现权限检查逻辑
    // 例如检查用户角色、权限列表等
    return true
  }

  // 更新用户信息
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...updates }
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  return {
    // 状态
    userInfo,
    isLoggedIn,
    
    // 计算属性
    isAuthenticated,
    
    // 方法
    initAuth,
    login,
    logout,
    clearAuth,
    hasPermission,
    updateUserInfo
  }
})
